<?php

namespace app\admin\controller\miniapp;

use app\common\controller\Backend;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\Client;
use uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\ServiceProvider;
use EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Application as MiniProgram;
use think\Cache;
use uctoo\ThinkEasyWeChat\Facade;

/**
 * 小程序云开发
 *
 * @icon fa fa-circle-o
 */
class Cloud extends Backend
{
    
    /**
     * Cloud模型对象
     * @var \app\admin\model\miniapp\Cloud
     */
    protected $model = null;
    protected $openPlatform;    //第三方平台
    /**
     * @var MiniProgram $miniapp
     */
    protected $miniapp;         //已在第三方平台授权的小程序
    /**
     * @var Client $cloud_env
     */
    protected $cloud_env;       //小程序对应云环境

    /**
     * 引入微信控制器的traits
     */
    use \app\wechatopen\library\traits\Wechatopen;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\miniapp\Cloud;
        $this->view->assign("statusList", $this->model->getStatusList());
        $wechatopenInfoConfig = Cache::get('wechatopen_config');
        $this->openPlatform = Facade::openPlatform($wechatopenInfoConfig['app_id'],$wechatopenInfoConfig);
        $applet = session('applet_info');
        $miniappinfo = $applet['miniprograminfo'];
        if(!isset($miniappinfo)){
            $this->error(__('Select miniapp to operate'));
        }
        $this->miniapp = $this->openPlatform->miniProgram($applet['appid'], $applet['authorizer_refresh_token']);
        $this->cloud_env = $this->miniapp->register(new ServiceProvider)->cloud_env;
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','wechatapplet_id','appid','alias','env','package_name','status']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取云环境信息
     */
    public function getenv($ids = '')
    {
        $applet = session('applet_info');
        $miniappinfo = $applet['miniprograminfo'];
        if(!isset($miniappinfo)){
            $this->error(__('Select miniapp to commit'));
        }
        $res = $this->cloud_env->getEnvInfo();
        trace('getenv','debug');
        trace($res,'debug');
        $this->wxResult($res, 'submit_audit', function ($data) use ($ids,$applet) {
            foreach ($data['info_list'] as $key => $env_info) {
                $env_model = new \app\admin\model\miniapp\Cloud;
               // $env_info = $env_info[0];
                trace($key,'debug');
                trace($env_info,'debug');
                $env_data = $env_model->where('env',$env_info['env'])->find();
                if($env_data){          //已有数据更新
                    trace('update','debug');
                    trace($env_data,'debug');
                    $info_data['info_list'] = json_encode($env_info);
                    $info_data['alias'] = $env_info['alias'];
                    $info_data['package_name'] = $env_info['package_name'];
                    $info_data['status'] = $env_info['status'];
                    $env_model->where('env',$env_info['env'])->update($info_data);
                }else{                  //新增
                    trace('add','debug');
                    trace($env_model,'debug');
                    $env_info['wechatapplet_id'] = $applet['wechatapplet_id'];
                    $env_info['admin_id'] = $this->auth->id;
                    $env_info['appid'] = $applet['appid'];
                    $env_info['info_list'] = json_encode($env_info);

                    $env_model->allowField(true)->save($env_info);
                }

               // $this->model->save(['audit_status' => 2,'auditid' => $data['auditid']],['id' => $ids]);  //更新提交审核状态
            }

        });

        $this->success("获取云环境信息成功");
    }

}
